package com.gwtplatform.samples.hplace.client.product;

import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;

import com.guit.client.GuitPresenter;
import com.guit.client.View;
import com.guit.client.async.AbstractAsyncCallback;
import com.guit.client.binder.GuitBinder;
import com.guit.client.binder.ViewField;
import com.guit.client.place.Place;
import com.gwtplatform.samples.hplace.client.HasInnerText;
import com.gwtplatform.samples.hplace.client.HasVisible;
import com.gwtplatform.samples.hplace.client.HyperlinkI;
import com.gwtplatform.samples.hplace.client.breadcrumbs.Backeable;
import com.gwtplatform.samples.hplace.client.breadcrumbs.BreadcrumbsPresenter;
import com.gwtplatform.samples.hplace.client.product.ProductPresenter.ProductBinder;
import com.gwtplatform.samples.hplace.shared.GetProduct;
import com.gwtplatform.samples.hplace.shared.GetProductResult;
import com.gwtplatform.samples.hplace.shared.Product;

import java.util.ArrayList;

public class ProductPresenter extends GuitPresenter<ProductBinder> implements Place<Backeable<Integer>> {

    public static interface ProductBinder extends GuitBinder<ProductPresenter> {
    }
    
    @Inject
    public ProductPresenter(BreadcrumbsPresenter breadcrumbsPresenter) {
        this.breadcrumbsPresenter = breadcrumbsPresenter;
    }
    
    BreadcrumbsPresenter breadcrumbsPresenter;
    
    @ViewField
    HasInnerText title;
    
    @ViewField
    HasText price;
    
    @ViewField
    HasText quantity;
    
    @ViewField
    HasVisible productDetails;

    @ViewField
    HyperlinkI backLink;
    
    public void setMessage(String string) {
      title.setInnerText(string);
      productDetails.setVisible(false);
    }

    public void setProductDetails(Product product) {
        productDetails.setVisible(true);
        title.setInnerText(product.getName());
        price.setText(product.getPrice());
        quantity.setText(Integer.toString(product.getQuantity()));
    }

    @Override
    public void go(final Backeable<Integer> backeable) {
        ArrayList<String> backTokens = backeable.getBackTokens();
        final View view = getView();
        backLink.setTargetHistoryToken(backTokens.get(backTokens.size() - 1));
        commandService.execute(new GetProduct(backeable.getValue()), new AbstractAsyncCallback<GetProductResult>() {
            @Override
            public void success(GetProductResult result) {
                breadcrumbsPresenter.buildNavegation(result.getProduct().getName(), view, backeable);
                setProductDetails(result.getProduct());
            }
        });
    }
}
